<template>
  <div>
    <!--      面包屑导航-->

    <bread-list :navData="navData"></bread-list>

<!--    卡片视图-->
    <el-card>
<!--       添加角色按钮区域-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="openAddRoles">添加角色</el-button>
        </el-col>
      </el-row>
<!--      角色列表区-->
      <el-table
          :data="rolesList"
          stripe
          border
          height="480"
             >

        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row class="vcenter" :class="['bdbottom', index === 0 ? 'bdtop' : '']" v-for="(item1,index) in scope.row.children" :key="item1.id">
              <!--渲染一级权限-->
              <el-col :span="5">

                <el-tag >{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二级和三级权限-->
              <el-col :span="19">
<!--                渲染二级权限-->
                <el-row class="vcenter" :class=" index2 === 0 ? '' : 'bdtop' " v-for="(item2,index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag  type="success">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag  closable :disable-transitions="true" type="warning" v-for="(item3) in item2.children" :key="item3.id" @close="removeRight(scope.row,item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
<!--        索引列-->
        <el-table-column align="center" label="#" type="index"></el-table-column>
        <el-table-column align="center" label="角色名称" prop="roleName"></el-table-column>
        <el-table-column align="center" label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column align="center" label="操作" >
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRoleDialog(scope.row)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-s-tools" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
<!--    编辑用户角色弹窗-->
    <el-dialog
        title="修改角色"
        :visible.sync="editRoleDialogVisible"
        width="30%"

    >
      <!--        内容主体区-->
      <el-form :model="editRoleForm" :rules="editRoleFormRules" ref="editRoleFormRef" label-width="80px" status-icon >
        <el-form-item label="角色名称" prop="roleName">
          <el-input  v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleDesc">
          <el-input  v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--        对话框底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editUser()">确定</el-button>
      </span>
    </el-dialog>

    <!--    添加用户角色弹窗-->
    <el-dialog
        title="添加角色"
        :visible.sync="addRoleDialogVisible"
        width="30%"
    >
      <!--        内容主体区-->
      <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="80px" status-icon >
        <el-form-item label="角色名称" prop="roleName">
          <el-input  v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleDesc">
          <el-input  v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--        对话框底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addRole()">确定</el-button>
      </span>
    </el-dialog>
<!--    // 分配权限对话框-->
    <el-dialog title="分配权限" :visible.sync="setRoleDialogVisible" width="30%" @close="setRoleDialogClose">
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id"
       default-expand-all
       :default-checked-keys="defKeys"
         ref="treeRef"
      >
      </el-tree>
      <!--        对话框底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="setRoleRights()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BreadList from "../common/BreadList";
export default {
  name: "Roles",
  components:{
    BreadList
  },
  data(){
    return{
      //所有角色列表信息
      rolesList:[],
      // 当前角色id
      roleId:'',
      editRoleDialogVisible:false, //控制用户权限对话框关闭与显示
      addRoleDialogVisible:false,//控制添加角色对话框关闭与显示
      setRoleDialogVisible:false,// 控制分配角色权限的对话框
      editRoleForm:{
        roleName:'',
        roleDesc:''
      },
      navData:{
        navNameFir:'权限管理',
        navSecond:'角色列表',
        path:'/home'
      },
      addRoleForm:{
        roleName:'',
        roleDesc:''
      },
      editRoleFormRules:{ // 表单的验证规则
        roleName:[
          { required:true, message:'请输入角色名称',trigger:'blur'},
        ],
        roleDesc:[
          {  message:'请输入角色描述',trigger:'blur'},
        ],
      },
      addRoleFormRules:{
        roleName:[
          { required:true, message:'请输入角色名称',trigger:'blur'},
        ],
        roleDesc:[
          {  message:'请输入角色描述',trigger:'blur'},
        ],
      },
      rightsList:[], // 所有权限列表
      treeProps:{  //树形对象的属性绑定属性
        children:'children',
        label:'authName'
      },
      defKeys:[] // 树形结构中，默认选中的节点id
    }
  },
  mounted() {
    this.getRolesList()
  },
  methods:{
    async getRolesList(){
      const {data:res}  = await this.$http.get('roles')
      if(res.meta.status === 200){
        this.rolesList = res.data
        this.$message.success(res.meta.msg)
      }else {
        this.$message.error(res.meta.msg)
      }
    },
    // 移除角色权限
    async removeRight(roleId,rightId){
      const confirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(e => e)
      if(confirm === 'confirm'){
        await this.deleteUser(roleId,rightId)
      }else {
        this.$message.info('已取消删除')
      }
      console.log(confirm)
    },
    //删除角色权限
    async deleteUser(role,rightId){
      const {data:res} = await this.$http.delete('roles/' + role.id + '/rights/' + rightId)
      const { meta:meta } = res
      if(meta.status === 200){
        this.$message.success('删除成功！')
        // await this.getRolesList()
        role.children = res.data
      }else {
        this.$message.error('删除失败！')
      }
    },
    // 打开角色权限弹窗
    openEditDialog(role){
      this.editRoleDialogVisible = true
      this.roleId = role.id
      this.editRoleForm.roleName = role.roleName
      this.editRoleForm.roleDesc = role.roleDesc
    },
    // 提交权限修改
    editUser(){
      this.$refs.editRoleFormRef.validate(async valid =>{
        if(valid){
           const { data:res } = await this.$http.put('roles/' + this.roleId,this.editRoleForm)
           const { meta:meta } = res
           if(meta.status === 200){
             this.$message.success('角色修改成功！')
             await this.getRolesList()
             this.editRoleDialogVisible =  false
           }else {
             this.$message.error('角色修改失败！')
           }
        }
      })
    },
    async deleteRoleDialog(role){
      const confirm = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(e => e)
      if(confirm === 'confirm'){
        await this.deleteRole(role.id)
        await this.getRolesList()
      }else {
        this.$message.info('已取消删除')
      }
      // console.log(confirm)
    },
    // 删除角色
    async deleteRole(roleId){
      const {data:res} = await this.$http.delete('roles/' + roleId)
      const { meta:meta } = res
      if(meta.status === 200){
        this.$message.success('删除成功！')
        await this.getRolesList()
      }else {
        this.$message.error('删除失败！')
      }
    },
    // 添加角色
    openAddRoles(){
      this.addRoleDialogVisible = true
    },
    addRole(){
      this.$refs.addRoleFormRef.validate(  async valid =>{
        if(valid){
          const {data:res} = await this.$http.post('roles',this.addRoleForm)
          if(res.meta.status === 201){
            this.addRoleDialogVisible = false
            this.$message.success(res.meta.msg)
            await this.getRolesList()
          }else {
            this.$message.error(res.meta.msg)
            this.addRoleDialogVisible = false
          }
          // console.log(...res)
        }
      })
    },
    showSetRightDialog(role){ //打开设置角色对话框
      this.getAllRolesRights()
      this.roleId = role.id
      this.getLeafKey(role,this.defKeys)
      this.setRoleDialogVisible = true
      if(role.children){
        console.log(role.children)
      }

      // console.log(role);

    },
    // 通过递归的形式，获取角色下全部的三级权限的id,并保存到defKey中
    getLeafKey(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach((item) =>{
        this.getLeafKey(item,arr)
      })
    },
    async getAllRolesRights(){
      const {data:res} =  await this.$http.get('rights/tree')
      const { meta:meta } = res
      if(res.meta.status === 200){
        this.rightsList = res.data
      }else {
        this.$message.error(meta.msg)
      }
      // console.log(res);
    },
    //关闭设置权限对话框
    setRoleDialogClose(){
      this.defKeys = []
    },
    //给角色添加权限
    setRoleRights(){
     const  keys = [
         ...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()
     ]
      const ids = keys.join(',')
      this.setRights(ids)
      console.log(ids);
    },
    // 设置权限
    async setRights(ids){
     const {data:res } =  await this.$http.post('roles/'+ this.roleId + '/rights',{rids:ids})
      const { meta:meta } = res
      if(meta.status === 200){
        await this.getRolesList()
        this.setRoleDialogVisible = false
        this.$message.success(meta.msg)
      }else {
        this.$message.error(meta.msg)
      }
      console.log(res);
    }
  }
}
</script>

<style scoped lang="less">

.el-tag{
  margin: 15px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>